# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
import json

from itemadapter import ItemAdapter
from kafka import KafkaProducer

from scrapy.utils.project import get_project_settings
import pymysql

# class HotRankPicPipeline:
#
#     def process_item(self, item, spider):
#         print(item)
#         return item


class MysqlPipeline:
    def open_spider(self, spider):
        settings = get_project_settings()
        self.host = settings['DB_HOST']
        self.port = settings['DB_PORT']
        self.user = settings['DB_USER']
        self.password = settings['DB_PASSWORD']
        self.name = settings['DB_NAME']
        self.charset = settings['DB_CHARSET']

        self.connect()

    def connect(self):
        self.conn = pymysql.connect(
            host=self.host,
            port=self.port,
            user=self.user,
            password=self.password,
            db=self.name,
            charset=self.charset
        )

        self.cursor = self.conn.cursor()

    def process_item(self, item, spider):
        sql = 'insert into hot_barrage(bvid,cid,content,sendtime,senddate) values ("{}","{}","{}","{}","{}")'.format(
            item['bvid'], item['cid'], item['content'], item['sendtime'], item['senddate']
        )
        self.cursor.execute(sql)
        self.conn.commit()

        # 开启后提交到kafka消息队列
        self.process_item_to_kafka(item)

        return item

    def close_spider(self, spider):
        self.cursor.close()
        self.conn.close()

    def process_item_to_kafka(self, item):

        self.producer = KafkaProducer(value_serializer=lambda v: json.dumps(v).encode('gbk'),
                                      bootstrap_servers=['master:9092'])

        tmp = {
            'bvid': item["bvid"],
            'cid': item["cid"],
            'content': item["content"],
            'sendtime': item["sendtime"],
            'senddate': item["senddate"]
        }

        self.producer.send('danmaku_list', tmp)
        pass